<template>
  <div>
    <h2>创建合同</h2>

    <form @submit.prevent="submitForm">
      <!-- 客户信息 -->
      <h3>客户信息</h3>
      <label>公司名称：</label>
      <input v-model="customer.companyName" required><br>

      <label>联系人：</label>
      <input v-model="customer.contactName" required><br>

      <label>联系方式：</label>
      <input v-model="customer.contactInfo"><br>

      <!-- 项目经理信息 -->
      <h3>项目经理信息</h3>
      <label>姓名：</label>
      <input v-model="employee.name" required><br>

      <label>联系方式：</label>
      <input v-model="employee.contactInfo"><br>

      <label>职位：</label>
      <select v-model="employee.position" required>
        <option value="PROJECT_MANAGER">项目经理</option>
        <option value="TECHNICIAN">技术人员</option>
        <option value="ADMIN">管理员</option>
      </select><br>

      <!-- 合同信息 -->
      <h3>合同信息</h3>
      <label>合同名称：</label>
      <input v-model="contract.name" required><br>

      <label>状态：</label>
      <select v-model="contract.status" required>
        <option value="DRAFT">草稿</option>
        <option value="ACTIVE">进行中</option>
        <option value="COMPLETED">已完成</option>
        <option value="CANCELLED">已取消</option>
      </select><br>

      <button type="submit">提交</button>
    </form>

    <p v-if="successMessage" style="color: green;">{{ successMessage }}</p>
  </div>
</template>

<script>
import customerService from '@/services/customerService';
import employeeService from '@/services/employeeService';
import contractService from '@/services/contractService';

export default {
  data() {
    return {
      customer: {
        companyName: '',
        contactName: '',
        contactInfo: ''
      },
      employee: {
        name: '',
        contactInfo: '',
        position: 'PROJECT_MANAGER'
      },
      contract: {
        name: '',
        status: 'DRAFT'
      },
      successMessage: ''
    };
  },
  methods: {
    async submitForm() {
      try {
        // 1. 创建客户
        const customerRes = await customerService.createCustomer(this.customer);
        const customerId = customerRes.data.id;

        // 2. 创建员工
        const employeeRes = await employeeService.createEmployee(this.employee);
        const employeeId = employeeRes.data.id;

        // 3. 创建合同
        const contractData = {
          ...this.contract,
          customerId,     // 使用刚创建的客户ID
          projectManagerId: employeeId  // 使用刚创建的项目经理ID
        };

        const contractRes = await contractService.createContract(contractData);

        this.successMessage = '合同创建成功！合同ID：' + contractRes.data.id;

        // 可选：清空表单或跳转到合同详情页
        this.$router.push({ name: 'ContractList' }); // 如果已配置路由

      } catch (error) {
        console.error('创建失败:', error);
        alert('创建失败，请检查网络或后端接口');
      }
    }
  }
};
</script>